package com.kll.tv.views

import android.graphics.Color
import android.view.View
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.GetAddressResponse
import com.kll.carolinehmibiz.net.bean.GetRegionResponse
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.listener.AddressDetailProtocol
import com.kll.carolinehmibiz.presentation.presenter.AddressDetailPresenter
import com.kll.tv.base.views.BaseActivity
import com.kll.tv.databinding.ActivityAddressDetailBinding
import com.kll.tv.utils.AppToast
import com.kll.tv.views.ui.pickerview.builder.OptionsPickerBuilder
import com.kll.tv.views.ui.pickerview.view.OptionsPickerView
import com.tencent.qcloud.tuicore.util.SoftKeyBoardUtil


/**
 * 收货地址详情页
 */
class AddressDetailActivity: BaseActivity<AddressDetailPresenter>(), AddressDetailProtocol.IView {
    private lateinit var binding: ActivityAddressDetailBinding
    private var data: GetAddressResponse? = null
    private var isFrom = 0 // 1- 编辑 0- 新增
    private var userAddressId = 0
    private var regionList = arrayListOf<Int>() // 地区
    private var isLoad = false


    override fun initViewBinding(): View {
        binding = ActivityAddressDetailBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): AddressDetailPresenter {
        return AddressDetailPresenter(this, this)
    }

    override fun init() {
        isFrom = intent.getIntExtra("isFrom", 0)

        // 编辑
        if (isFrom == 1) {
            binding.tvDelete.visibility = View.VISIBLE // 显示删除按钮
            data = intent.getBundleExtra("data")!!.getSerializable("data") as GetAddressResponse // 获取数据
            if (data != null) {
                userAddressId = data!!.user_address_id // 收货地址id
                binding.edtName.setText(data?.consignee) // 收货人
                binding.edtPhone.setText(data?.mobile) // 收货手机号
                regionList = data!!.region_list // 所在地区编号数组
                binding.tvRegionValue.setText(data?.region) // 所在地区
                binding.edtDetailAddress.setText(data?.address) // 详细地址
                binding.swDefault.isChecked = if (data?.is_default == 1) true else false // 是否为默认地址
            }
        } else { // 新增
            binding.tvDelete.visibility = View.GONE // 隐藏删除按钮
        }

        loadData()
        initListener()
    }

    private fun loadData() {
        // 加载地区列表
        mPresenter.getRegion(1)
    }

    private fun initListener() {
        binding.ivBack.setOnClickListener { finish() }
        // 选择地区
        binding.tvRegionValue.setOnClickListener {
            if (isLoad) {
                showPickerView()
            }
        }
        // 保存
        binding.tvSave.setOnClickListener {
            if (isFrom == 1) {
                // 编辑
                if (binding.edtName.text.toString().trim() == "" || binding.edtPhone.text.toString().trim() == ""
                    || binding.edtDetailAddress.toString().trim() == "" || regionList.size < 2) {
                        AppToast.show("请输入完整信息在操作！", 2000)
                        return@setOnClickListener
                } else {
                    mPresenter.editAddress(userAddressId, binding.edtName.text.toString().trim(), regionList,
                        binding.tvRegionValue.text.toString(), binding.edtDetailAddress.text.toString().trim(),
                        binding.edtPhone.text.toString().trim(), if (binding.swDefault.isChecked) 1 else 0)
                }
            } else {
                // 新建
                if (binding.edtName.text.toString().trim() == "" || binding.edtDetailAddress.toString().trim() == ""
                    || binding.edtPhone.text.toString().trim() == "" || regionList.size < 2) {
                        AppToast.show("请输入完整信息在操作！", 2000)
                        return@setOnClickListener
                } else {
                    mPresenter.addAddress(binding.edtName.text.toString().trim(), regionList, binding.edtDetailAddress.text.toString().trim(),
                        binding.edtPhone.text.toString().trim(), if (binding.swDefault.isChecked) 1 else 0)
                }
            }
        }
        // 删除
        binding.tvDelete.setOnClickListener {
            mPresenter.delAddress(intArrayOf(userAddressId))
        }

        binding.edtPhone.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtPhone.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtPhone)
                }
            }

        })
        binding.edtName.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtName.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtName)
                }
            }

        })
        binding.edtDetailAddress.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtDetailAddress.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtDetailAddress)
                }
            }

        })
    }

    private fun showPickerView() { // 弹出选择器
        // 弹出选择器
        val pvOptions: OptionsPickerView<GetRegionResponse> = OptionsPickerBuilder(
            this
        ) { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
            val opt1tx = if (mPresenter.provinces.size > 0) mPresenter.provinces[options1].region_name else ""
            val opt2tx = if (mPresenter.citys.size > 0
                && mPresenter.citys[options1].size > 0
            ) mPresenter.citys[options1][options2].region_name else ""
            val opt3tx =
                if (mPresenter.citys.size > 0 && mPresenter.areas[options1].size > 0 && mPresenter.areas[options1][options2].size > 0
                ) mPresenter.areas[options1][options2][options3].region_name else ""
            val tx = opt1tx + opt2tx + opt3tx
            binding.tvRegionValue.text = tx
            regionList.clear()
            regionList.add(mPresenter.provinces[options1].region_id)
            regionList.add(mPresenter.citys[options1][options2].region_id)
            regionList.add(mPresenter.areas[options1][options2][options3].region_id)
        }
            .setTitleText("城市选择")
            .setDividerColor(Color.BLACK)
            .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
            .setContentTextSize(30)
            .setTitleSize(30)
            .setSubCalSize(30)
            .build()

        pvOptions.setPicker(mPresenter.provinces,
            mPresenter.citys as List<List<GetRegionResponse>>?, mPresenter.areas as List<List<List<GetRegionResponse>>>?
        ) //三级选择器

        pvOptions.show()
    }

    /**
     * 获取地区成功回调
     */

    override fun getRegionSuccessed() {
        isLoad = true
    }

    /**
     * 获取地区失败回调
     */
    override fun getRegionFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.getRegion(1)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 添加地址成功回调
     */
    override fun addAddressSuccessed() {
        AppToast.show("添加成功！", 2000)
        setResult(1)
        finish()
    }

    /**
     * 添加地址失败回调
     */
    override fun addAddressFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.addAddress(binding.edtName.text.toString().trim(), regionList, binding.edtDetailAddress.text.toString().trim(),
                        binding.edtPhone.text.toString().trim(), if (binding.swDefault.isChecked) 1 else 0)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 编辑地址成功回调
     */
    override fun editAddressSuccessed() {
        AppToast.show("编辑成功！", 2000)
        setResult(1)
        finish()
    }

    /**
     * 编辑地址失败回调
     */
    override fun editAddressFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.editAddress(userAddressId, binding.edtName.text.toString().trim(), regionList,
                        binding.tvRegionValue.text.toString(), binding.edtDetailAddress.text.toString().trim(),
                        binding.edtPhone.text.toString().trim(), if (binding.swDefault.isChecked) 1 else 0)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 删除地址成功回调
     */
    override fun delAddressSuccessed() {
        AppToast.show("删除成功！", 2000)
        setResult(1)
        finish()
    }

    /**
     * 删除地址失败回调
     */
    override fun delAddressFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.delAddress(intArrayOf(userAddressId))
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

}